<?php

declare(strict_types=1);

namespace App\AdminApi;

use App\Application;
use App\Common\Extend\Guard\Guard;
use App\Common\Extend\Guard\ModelInterface;
use App\Common\GuardModel\AdminGuard;
use Zms\Exception\{
    AppException, DataException, ExpireLoggedInException, NotLoggedException
};

class BasicsController extends \Core\Basics\BasicsController
{

    /**
     * 应用标识
     * @var string
     */
    const APP = Application::APP['ADMIN']['NAME'];

    /**
     * 用户组
     */
    const GUARD = Application::APP['ADMIN']['GUARD'];

    /**
     * 服务
     */
    const SERVER = Application::APP['ADMIN']['SERVER'];


    /**
     * 获取分页信息
     * @param int $default
     * @return int
     */
    protected function pageSize(int $default = 15): int
    {
        $size = (int)$this->request->input('size', 0);
        return $size ?: $default;
    }

    /**
     * 获取当前分页
     * @return int
     */
    protected function page(): int
    {
        return (int)$this->request->input('page', 1);
    }


    /**
     * 获取排序
     * @param string $default
     * @return string
     */
    final protected function orderBy(string $default = "`id` DESC"): string
    {
        $sort = $this->request->input('sort');
        if (!$sort) return $default;
        if (str_starts_with($sort, '-')) {
            $sort = substr($sort, 1);
            return "`$sort` ASC";
        }
        return "`$sort` DESC";
    }

    /***
     * @describe 获取搜索条件
     * @user zlf <zms-pro@qq.com> 2025/3/10
     * @return mixed
     */
    public function query(): array
    {
        $query = $this->request->query();
        unset($query['page']);
        unset($query['size']);
        return $query;
    }


    /**
     * 获取授权组件
     * @return Guard
     * @throws AppException
     * @throws DataException
     */
    protected function guard(): Guard
    {
        return guard(self::GUARD);
    }


    /**
     * 管理员信息
     * @return ModelInterface|AdminGuard
     * @throws AppException
     * @throws DataException
     * @throws ExpireLoggedInException
     * @throws NotLoggedException
     */
    protected function user(): AdminGuard|ModelInterface
    {
        return $this->guard()->user();
    }


    /**
     * 数据权限
     * @return array
     */
    protected function dataAuth(): array
    {
        return $this->user()->dataAuth();
    }


    /**
     * 是否已登录
     * @return bool
     * @throws AppException
     * @throws DataException
     */
    public function isLogin(): bool
    {
        return $this->guard()->tourist() === false;
    }
}